<template>
  <div>
    <div class="customer" v-if="!customerAddShow && !followAddShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['erp:customer:query']"
          class="btn search"
          @click="getCustomerList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-hasPermi="['erp:customer:add']"
          class="btn search"
          @click="
            customerAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="customerNum">客户编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="name">客户名称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="customerAddress">单位地址</el-checkbox>
            </div>
            <div>
              <el-checkbox label="legalPerson">企业法人</el-checkbox>
            </div>
            <div>
              <el-checkbox label="uscc">社会统一信用代码</el-checkbox>
            </div>
            <div>
              <el-checkbox label="createUser">创建人员</el-checkbox>
            </div>
            <div>
              <el-checkbox label="userName">业务人员</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deptName">业务部门</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>

      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.name"
            class="search-input"
            maxlength="30"
            placeholder="请输入客户名称"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.customerAddress"
            class="search-input"
            maxlength="30"
            placeholder="请输入单位地址"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.legalPerson"
            class="search-input"
            maxlength="30"
            placeholder="请输入企业法人"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.createUser"
            class="search-input"
            maxlength="30"
            placeholder="请输入创建人"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.userId"
            class="search-input"
            maxlength="30"
            placeholder="请输入业务员"
          ></el-input>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="customerList"
        border
        height="64vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @sort-change="sortChange"
      >
        <!-- 操作模式 -->
        <el-table-column
          label="操作"
          :show-overflow-tooltip="true"
          width="180px"
        >
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-hasPermi="['erp:customer:edit']"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-hasPermi="['erp:customer:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-hasPermi="['erp:customer:follow']"
                title="跟进"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('follow', row)"
              >
                <DocumentChecked />
              </el-icon>
              <el-icon
                v-hasPermi="['erp:customer:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="70"
          align="center"
        />
        <el-table-column
          v-if="checkList.includes('customerNum')"
          label="客户编号"
          prop="customerNum"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          v-if="checkList.includes('name')"
          label="客户名称"
          prop="name"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          v-if="checkList.includes('customerAddress')"
          label="单位地址"
          prop="customerAddress"
          :show-overflow-tooltip="true"
          min-width="200"
          sortable="custom"
        />
        <el-table-column
          v-if="checkList.includes('legalPerson')"
          label="企业法人"
          prop="legalPerson"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          v-if="checkList.includes('uscc')"
          label="社会统一信用代码"
          prop="uscc"
          :show-overflow-tooltip="true"
          min-width="130"
          sortable="custom"
        />
        <el-table-column
          v-if="checkList.includes('createUser')"
          label="创建人员"
          prop="createUser"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          v-if="checkList.includes('userName')"
          label="业务人员"
          prop="userName"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          v-if="checkList.includes('deptName')"
          label="业务部门"
          prop="deptName"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getCustomerList"
      />
    </div>
    <CustomerAdd
      ref="customerAddRef"
      v-if="customerAddShow"
      v-model:customerAddShow="customerAddShow"
      @updateFollowAddShow="followAddShow = false"
      @refreshList="getCustomerList"
      :pageType="pageType"
    />
    <FollowAdd
      ref="followAddRef"
      v-model:followAddShow="followAddShow"
      @refreshList="getCustomerList"
      :pageType="pageType"
      v-if="followAddShow"
    />
  </div>
</template>

<script setup>
import CustomerAdd from "./customerAdd.vue";
import FollowAdd from "./followAdd.vue";
import {
  getCustomerListApi,
  deleteCustomerApi,
} from "@/api/information/customer";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
// 搜索参数
const params = reactive({
  createUser: "",
  customerAddress: "",
  legalPerson: "",
  name: "",
  userId: "",
  pageNum: 1,
  pageSize: 50,
  sortField: "",
  sortOrder: "",
});
const checkList = ref([
  "customerNum",
  "name",
  "customerAddress",
  "legalPerson",
  "uscc",
  "createUser",
  "userName",
  "deptName",
]);

// 表格加载效果
const loading = ref(false);
// 客户列表
const customerList = ref([]);
// 总数
const total = ref(0);
// 客户新增组件引用
const customerAddRef = ref(null);
// 客户新增组件显隐
const customerAddShow = ref(false);
// 跟进新增组件显隐
const followAddShow = ref(false);
// 跟进组件引用
const followAddRef = ref(null);
// 操作类型
const pageType = ref("");
/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: 0,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 0,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getCustomerList();
};

/**
 * @description: 获取客户列表
 */
const getCustomerList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    const res = await getCustomerListApi({ pageNum, pageSize }, params);
    customerList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 重置
 */
const handleRefresh = () => {
  Object.assign(params, {
    createUser: "",
    customerAddress: "",
    legalPerson: "",
    name: "",
    userId: "",
    pageNum: 1,
    pageSize: 50,
    sortField: "",
    sortOrder: "",
  });
  getCustomerList();
};

/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "edit":
      pageType.value = type;
      customerAddShow.value = true;
      nextTick(() => {
        customerAddRef.value.handleDetailInfo(row.customerId);
      });
      break;
    case "detail":
      pageType.value = type;
      customerAddShow.value = true;
      followAddShow.value = true;
      nextTick(() => {
        customerAddRef.value.handleDetailInfo(row.customerId);
        followAddRef.value.handleDetailInfo(row.customerId);
      });
      break;
    case "follow":
      pageType.value = type;
      followAddShow.value = true;
      nextTick(() => {
        followAddRef.value.handleDetailInfo(row.customerId);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该客户资料，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteCustomerApi(row.customerId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getCustomerList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

onMounted(() => {
  getCustomerList();
  getTableHeader();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.customer {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
}
</style>
